package com.lwq.commentTool.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;


public class SqlUtil {
	public static Connection getSqlConnection(String url,String user,String psw){
		Connection conn = null;
		try {
			Class.forName("com.mysql.jdbc.Driver");
			conn = DriverManager.getConnection(url, user, psw);
			if (!conn.isClosed())
				System.out.println("Succeeded connecting to the Database!");
		} catch (ClassNotFoundException e) {
			System.out.println("Sorry,can`t find the Driver!");
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return conn;
	}
	
	public static Statement getStatement (String url,String user,String psw){
		Statement statement = null;
		Connection conn = getSqlConnection(url, user, psw);
		if(conn != null){
			try {
				statement = conn.createStatement();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return statement;
	}
	
	public static ResultSet querySql (Statement statement,String sql){
		ResultSet result = null;
		if(statement != null && sql != null){
			try {
				result = statement.executeQuery(sql);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return result;
	}
	
	public static List<String> getValue (Statement statement,String sql,String columnLabel){
		List<String> list = null;
		String val = null;
		ResultSet result = querySql(statement, sql);
		if(result != null){
			list = new ArrayList<String>();
		}
		try {
			while(result.next()){
				val = result.getString(columnLabel);
				list.add(val);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return list;
	}
}
